// pages/homeAdd_detail/homeAdd_detail.js
const app = getApp();
const db = wx.cloud.database();
Page({


  data: {
    image:[],
    Image:[]
  },

  uploadImage: function () {
    let that = this;
    wx.chooseImage({
      count:9,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        });
        console.log(res);
        // 返回选定照片的本地文件路径列表，tempFilePaths可以作为img标签的src属性显示图片
        let imagePath = res.tempFilePaths;
        that.setData({
          Image: imagePath
        });
        
        for(let i=0;i<res.tempFilePaths.length;i++){
          let filePath = res.tempFilePaths[i];
          that.uploadPhoto(filePath)
        }
      },
      fail: e => {
        console.error('[上传图片] 失败：', e)
      },
      complete: () => {
        wx.hideLoading()
      }
    });
  },

  uploadPhoto:function (filePath) {
    
    wx.cloud.uploadFile({
      filePath:filePath,
      cloudPath:"photo/"+Date.now()+".jpg",
      success:(res)=>{
        var fid = res.fileID;
        this.data.image.push(fid);
        resolve();
      }
    })
  },
  // 重置图片
  rebulid:function(){
    let that = this;
    that.setData({
      Image:[],
      image:[]
    })
  },



  // 提交数据
  submit: function () {
    let image = this.data.image;
    let kind = this.data.kind;
    let address = this.data.address;
    let time = this.data.time;
    let detail = this.data.detail;
    

    // 判断有无填写完成数据
    if(image && address && time && detail ){
      db.collection("home_list").add({
        data: {
          image: image,
          kind:kind,
          address: address,
          time: time,
          detail: detail,
          openid:app.globalData.openid
        }
      }).then(res => {
        wx.showToast({
          title: '提交成功,感谢您为宝贝们作出的贡献',
          duration: 3000
        }).then(res=>{
          wx.switchTab({
            url:'../home/home'
        })
        })
  })
    }else{
      wx.showToast({
        title: '有数据未完成填写',
        duration: 3000
      })
    }

  }
})
